const router = require( 'koa-router' )();
const path = require( 'path' );
const fs = require( 'fs' );

const appSetting = require( '../setting' );

const textUtils = require( '../utils/text_utils' );
const akUtils = require( '../utils/ak_utils' );
const redisUtils = require( '../utils/redis_utils' );
const cacheKeyUtils = require( '../utils/cache_key_utils' )

const projects = require( '../models/projects' );

const defaultThumbPath = path.join( __dirname, '../static/default.png' );
const defaultThumb = fs.readFileSync( defaultThumbPath, 'base64' );
const defaultThumbBinary = new Buffer( defaultThumb, 'base64' );

const headers = { 'Content-Type': 'application/json', 'Encoding': 'utf8' };

const list = async function ( ctx, next ) {

    ctx.set( headers );

    var page = parseInt( ctx.query.page ) || 0;
    var limit = parseInt( ctx.query.limit ) || 6;
    var orderBy = ctx.query.orderBy || 'update_at';
    var order = ctx.query.order || 'desc';
    var offset = page * limit;
    var search = ctx.query.search;

    var params = {
        userId: ctx.request.cookies.userId,
        orderBy: orderBy,
        order: order,
        limit: limit + 1,
        offset: offset,
        search: search
    };

    var results = await projects.list( params );

    if ( !results ) {

        ctx.body = { code: 1, msg: '查询发生错误' };

    } else {

        var dataArray = [];
        results.forEach( function ( result ) {
            dataArray.push( {
                uid: result.uid,
                title: result.title,
                desc: result.description,
                share: result.share,
                updateAt: new Date( result.update_at ).getTime()
            } );
        } );
        var hasNext = dataArray.length > limit;
        if ( hasNext ) {
            dataArray.splice( limit );
        }
        ctx.body = {
            code: 0,
            data: {
                page: page,
                hasNext: hasNext,
                items: dataArray
            }
        };

    }

};

const create = async function ( ctx ) {

    ctx.set( headers );

    var userId = ctx.request.cookies.userId;
    var title = ctx.request.body.title;
    var desc = ctx.request.body.desc;
    var content = ctx.request.body.content || '';

    if ( textUtils.stringIsBlank( title ) ) {
        ctx.body = { 'code': 1, 'msg': '缺少参数' };
        return;
    }

    var params = {
        uid: textUtils.genUid(),
        userId: userId,
        title: title,
        desc: desc,
        content: content,
        thumb: defaultThumbBinary
    };

    // 插入记录的同时，获取分享AK

    var ak = await akUtils.getAutoGeneratedAk( userId );

    if ( !ak ) {
        return;
    }

    try {
        var result = await projects.insert( params );
        if ( result ) {
            ctx.body = {
                code: 0,
                data: {
                    title: title,
                    desc: desc,
                    uid: params.uid,
                    ak: ak.key
                }
            }
        }

    } catch ( e ) {
        ctx.body = { code: 1, msg: '新建发生错误' };
    }

};

const update = async function ( ctx ) {

    ctx.set( headers );

    var userId = ctx.request.cookies.userId;
    var uid = ctx.params.uid;
    var title = ctx.request.body.title;
    var desc = ctx.request.body.desc;
    var content = ctx.request.body.content || '';
    var share = ctx.request.body.share || false;

    if ( textUtils.stringIsBlank( uid ) || textUtils.stringIsBlank( title ) ) {
        ctx.body = { 'code': 1, 'msg': '缺少参数' };
        return;
    }

    var contentJson = content;

    var params = {
        userId: userId,
        uid: uid,
        title: title,
        desc: desc,
        content: content,
        share: share
    };

    try {
        var result = await projects.update( params );

        if ( share ) {
            akUtils.getAutoGeneratedAk( userId, function ( err, result ) {
                if ( result ) {
                    var ak = result.key;
                    var appPath = 'apps';
                    var domain = appSetting.getSetting( 'site.domain' );
                    var appConfig = config.getAppConf();
                    var appEnv = ( !appConfig || !appConfig.env ) ? 'prod' : appConfig.env;
                    var protocol = appEnv == 'prod' ? 'https' : 'http';
                    var shareUrl = protocol + '://' + domain + '/apps/data_insights/' + uid + '/share?ak=' + ak;
                    // 获取public data list
                    var pubDataList = [];
                    if ( contentJson && contentJson instanceof Array ) {
                        contentJson.forEach( function ( data ) {
                            if ( data.dataType == 'public' ) {
                                pubDataList.push( data.dataUid );
                            }
                        } );
                    }

                    // GalleryUtils.share( uid, userId, appName, appPath, title, desc, shareUrl, pubDataList );
                }
            } );
        } else {

            // GalleryUtils.cancelShare( uid, userId );

        }
        //
        ctx.body = { code: 0 };
    } catch ( e ) {
        ctx.body = { code: 1, msg: '保存发生错误' };
    }

};

const get = async function ( ctx ) {

    ctx.set( headers );

    var userId = ctx.request.cookies.userId;
    var uid = ctx.params.uid;

    if ( textUtils.stringIsBlank( uid ) || textUtils.stringIsBlank( userId ) ) {
        ctx.body = { 'code': 1, 'msg': '缺少参数' };
        return;
    }

    var params = {
        userId: userId,
        uid: uid
    };

    var ak = await akUtils.getAutoGeneratedAk( userId );

    if ( !ak ) {
        return;
    }

    try {
        var results = await projects.get( params );
        if ( !results ) {
            ctx.body = { code: 1, msg: '获取项目信息发生错误' };
        } else if ( results.length === 0 ) {
            ctx.body = { code: 1, msg: '项目不存在' };
        } else {
            var data = results[ 0 ];
            if ( data.content ) {
                data.content = JSON.parse( data.content );
            }
            data.desc = data.description;
            delete data.description;
            data.ak = ak.key;
            ctx.body = {
                code: 0,
                data: data
            };
        }
    } catch ( e ) {
        console.log( e )
        ctx.body = { code: 1, msg: '获取项目信息发生错误' };
    }

};

const remove = async function ( ctx ) {

    ctx.set( headers );

    var uid = ctx.params.uid;
    var userId = ctx.request.cookies.userId;

    if ( textUtils.stringIsBlank( uid ) ) {
        ctx.body = { 'code': 1, 'msg': '缺少参数' };
        return;
    }

    var params = {
        uid: uid,
        userId: userId
    };

    try {
        var result = await projects.remove( params );
        if ( result ) {
            ctx.body = { code: 0 };
        }
    } catch ( e ) {
        ctx.body = { code: 1, msg: '删除发生错误' };
    }

};


const updateThumb = async function ( ctx ) {

    ctx.set( headers );

    var userId = ctx.request.cookies.userId;
    var uid = ctx.params.uid;
    var thumb = ctx.request.body.thumb;

    if ( textUtils.stringIsBlank( uid ) ) {
        ctx.body = { 'code': 1, 'msg': '缺少参数' };
        return;
    }

    let binary;

    if ( thumb === '' ) {

        binary = defaultThumbBinary

    } else {

        thumb = thumb.replace( /^data:image\/png;base64,/, '' );
        binary = new Buffer( thumb, 'base64' );

    }

    var params = {
        userId: userId,
        uid: uid,
        thumb: binary
    };

    try {
        var result = await projects.updateThumb( params );
        if ( result ) {
            ctx.body = { code: 0 };
        }
    } catch ( e ) {
        ctx.body = { code: 1, msg: '保存缩略图发生错误' };
    }


    // var result = await redisUtils.set( thumbKey, binary );

    // if ( !result ) {
    //     ctx.body = { code: 1, msg: '保存缩略图发生错误' };
    // } else {
    //     //
    //     var thumbKey = `app.insight.${ uid }.thumb`;
    //     redisUtils.set( thumbKey, binary );
    //     //
    //     ctx.body = { code: 0 };
    // }

};

const thumb = async function ( ctx ) {

    var uid = ctx.params.uid;

    if ( textUtils.stringIsBlank( uid ) ) {
        ctx.set( headers );
        ctx.body = { 'code': 1, 'msg': '缺少参数' };
        return;
    }

    var params = {
        uid: uid
    };

    var thumbKey = cacheKeyUtils.insightThumbKey( uid );

    var result = await redisUtils.get( thumbKey );

    if ( result && result.length > 0 ) {
        ctx.set( {
            'Content-Type': 'image/png',
            'Cache-Control': 'max-age=86400',
            'Access-Control-Max-Age': 86400,
            'Access-Control-Allow-Origin': '*'
        } );
        ctx.body = result;
        return;
    }

    try {
        var results = await projects.thumb( params );
        if ( !results ) {
            ctx.set( headers );
            ctx.body = { code: 1, msg: '获取缩略图发生错误' };
            return;
        } else {
            if ( results.length > 0 && results[ 0 ].thumb ) {
                //
                redisUtils.set( thumbKey, results[ 0 ].thumb );
                //
                ctx.set( {
                    'Content-Type': 'image/png',
                    'Cache-Control': 'max-age=86400',
                    'Access-Control-Max-Age': 86400,
                    'Access-Control-Allow-Origin': '*'
                } );
                ctx.body = results[ 0 ].thumb;
            } else {
                ctx.set( headers );
                ctx.body = { code: 1, msg: '没有缩略图' };
            }
        }
    } catch ( e ) {
        console.log( e )
        ctx.set( headers );
        ctx.body = { code: 1, msg: '获取缩略图发生错误' };
    }

};





router.get( '/list', list );

router.post( '/', create );

router.put( '/:uid', update );

router.get( '/:uid', get );

router.delete( '/:uid', remove );

router.post( '/:uid/thumb', updateThumb );

router.get( '/:uid/thumb', thumb );

module.exports = router;
